
/*
 * Serial Messages
 * 
*/


#include "serial.h"


// serial data receive buffer 
uint8_t rxBuffer[1024]={0};
uint16_t rxIndex=0;


// New LED Frame
bool newFrame;
// new Serial Message received
bool newMessage;
//All next Data are for Stream
bool streaming;

void checkMessage()
{
  Serial.println("Check Message");
  if (newMessage)
  {
    uint16_t i=0; //array index
    uint8_t data; // current working byte
    rgb_t c; // color
    uint8_t pos=0; //pixel position
    uint8_t seq;
    
    
    
    while(*rxBuffer)
    {
      data = rxBuffer[i];  
      if(data > 127)
      {
        switch (data) // check commands
        {
          case STARTSEQ:
                      seq = rxBuffer[++i];
                      Serial.print("Start Sequence ");
                      Serial.println(seq);
                      break;            
          case STOPSEQ:
                      Serial.println("Stopping Sequence");
                      break;
          case STARTSTREAM: streaming = true;
                            break;
          case STOPSTREAM:  streaming = false;
                            break;        
        }
      }
      else
      {
        if (streaming) // write color data direct into LED buffer
        {
          c.r = data;    // current value is red
          c.g = rxBuffer[++i]; //next value is green
          c.b = rxBuffer[++i]; // next is blue
          strip.setPixelColor(pos++,c);
      
          if (pos == STRIPSIZE) // show, if buffer is full
          {
            strip.show();
            pos = 0; 
          }  
        }
      }
      i++; // next byte      
    }
  }
  newMessage = false;
}



/**
* brief Serial Data receive Interrupt
*/
void serialEvent()
{
   while (Serial.available()) 
   {
    // get the new byte:
    uint8_t data = (uint8_t) Serial.read();
    
    if ((data = '\n') || (rxIndex == 1023)) 
      newMessage = true;
    else
      rxBuffer[rxIndex++] = data;  
  }
}
